package com.example.statistics.ui.purchase

import android.content.Intent
import android.view.View
import android.widget.TextView
import com.example.statistics.R
import com.example.statistics.bean.FinancingFeeBean
import com.example.statistics.bean.FuturesFeeBean
import com.example.statistics.bean.PurchaseProductBean
import com.example.statistics.bean.TaxFeeBean
import com.example.statistics.ex.*
import com.example.statistics.net.UrlConfig
import com.example.statistics.utils.Constants
import com.example.statistics.utils.activityForResult
import com.example.statistics.ex.contentText
import com.example.statistics.ex.onSingleLongClicked
import kotlinx.android.synthetic.main.activity_base_pruchase_product.*
import kotlinx.android.synthetic.main.activity_purchase_futures_product_edit.*
import kotlinx.android.synthetic.main.layout_purchase_type_title.view.*
import kotlinx.android.synthetic.main.table_row_futures_fee.view.*
import org.jetbrains.anko.find
import org.jetbrains.anko.sdk27.coroutines.onClick
import java.math.BigDecimal
import java.util.*
import kotlin.math.abs

/**
 * 期货
 */
class PurchaseFuturesProductActivity : BasePurchaseProductActivity() {


    private val futuresFeeArray = mutableMapOf<String, FuturesFeeBean>()
    private val financingTypeList = listOf("定金", "尾款", "税款")
    private val futuresFeeList = listOf("预付定金", "实际定金", "预估定金", "预付保证金", "实际保证金", "预付尾款", "实际尾款", "预估尾款")


    override val childrenViewRes: Int
        get() = R.layout.activity_purchase_futures_product_edit


    override val billTotalAmount: Double
        get() = futuresFee.addEx(taxFee).addEx(financingFee).addEx(clearanceFee).addEx(storageFee)
            .toDouble()


    override fun initView() {
        super.initView()
        layout_fee.visibility = View.VISIBLE
        layout_futures_title.tv_title.text = "货款"
        layout_tax.tv_title.text = "税款"
        layout_financing.tv_title.text = "融资款"
        layout_financing.iv_add.onClick {
            bottomSingleDialog(list = financingTypeList) { _, s ->
                val endDate = purchaseProductBean?.shippingInfo?.deliveryDate
                    ?: Date().format().orEmpty()
                if (s == "尾款") {
                    activityForResult<FinancingFeeEditActivity>(
                        Constants.TYPE to s,
                        Constants.AGENT_ID to purchaseProductBean?.agentId,//代理id，
                        Constants.PURCHASE_PRODUCT_ID to purchaseId,
                        Constants.CONTAINER_NO to containerNo,//采购商品的id
                        Constants.DATA to purchaseProductBean?.futuresFeeList, //货款
                        Constants.DATE to endDate
                    ) {
                        httpFinancingFee()
                    }
                } else if (s == "税款") {
                    activityForResult<FinancingFeeEditActivity>(
                        Constants.TYPE to s,
                        Constants.AGENT_ID to purchaseProductBean?.agentId,//代理id
                        Constants.PURCHASE_PRODUCT_ID to purchaseId,
                        Constants.CONTAINER_NO to containerNo,//采购商品的id
                        Constants.DATA to purchaseProductBean?.taxFee, //税款
                        Constants.DATE to endDate
                    ) {
                        httpFinancingFee()
                    }
                }
            }
        }


        layout_tax.iv_add.onClick {
            val totalPrice = purchaseProductBean?.productTotalPrice ?: 0.0
            activityForResult<TaxFeeActivity>(
                Constants.TITLE to title,
                Constants.AMOUNT to totalPrice,
                Constants.PURCHASE_PRODUCT_ID to purchaseId,
                Constants.DATA to purchaseProductBean?.taxFee,
                Constants.CONTAINER_NO to containerNo,
                Constants.TYPE to purchaseProductBean?.priceUnit
            ) {
                layout_tax.iv_add.visibility = View.GONE
                httpTaxFee()
            }
        }
        layout_futures_title.iv_add.onClick {
            futures()
        }
    }


    override fun initData(bean: PurchaseProductBean) {
        super.initData(bean)
        bean.futuresFeeList?.forEach {
            futuresFeeArray[it.feeType] = it
        }
        if (!bean.futuresFeeList.isNullOrEmpty()) {
            futuresFee(bean.futuresFeeList)
        }
        if (!bean.financingFeeList.isNullOrEmpty()) {
            financingFee(bean.financingFeeList)
        }
        if (bean.taxFee != null) {
            taxFee(bean.taxFee)
        }
    }

    /**
     * 货款
     */
    private fun futures() {
        if (purchaseProductBean != null) {
            val feeTypeList = purchaseProductBean?.futuresFeeList?.map { it.feeType }
            val resultList = futuresFeeList.filter { !feeTypeList.orEmpty().contains(it) }

            bottomSingleDialog(list = resultList) { _, s ->
                val futuresIntent = Intent(this, FuturesFeeActivity::class.java)
                futuresIntent.putExtra(Constants.TITLE, s)

                if (s == "实际定金" && futuresFeeArray["预估定金"] != null) {
                    futuresIntent.putExtra(Constants.DATA, futuresFeeArray["预估定金"])
                } else if (s == "实际保证金" && futuresFeeArray["预估保证金"] != null) {
                    futuresIntent.putExtra(Constants.DATA, futuresFeeArray["预估保证金"])
                } else if (s == "实际尾款" && futuresFeeArray["预估尾款"] != null) {
                    futuresIntent.putExtra(Constants.DATA, futuresFeeArray["预估尾款"])
                } else {
                    futuresIntent.putExtra(Constants.PURCHASE_PRODUCT_ID, purchaseId)
                    if (s == "预估定金")
                        futuresIntent.putExtra(Constants.DATE, futuresFeeArray["预付定金"]?.date)
                    else if (s == "预估尾款")
                        futuresIntent.putExtra(Constants.DATE, futuresFeeArray["预付尾款"]?.date)

                    //金额
                    val totalPrice = purchaseProductBean?.productTotalPrice ?: 0.0
                    val dollar = when (s) {
                        "预付定金" ->
                            totalPrice.mulEx(0.3)
                        "实际定金", "预估定金" ->
                            futuresFeeArray["预付定金"]?.dollar ?: totalPrice.mulEx(0.3)
                        "预付保证金", "实际保证金" ->
                            totalPrice.mulEx(0.3).subEx(futuresFeeArray["预付定金"]?.dollar)
                        "预估尾款", "预付尾款", "实际尾款" -> {
                            val deposit = futuresFeeArray["实际定金"]?.dollar ?: futuresFeeArray["预付定金"]?.dollar
                            val bail = futuresFeeArray["实际保证金"]?.dollar ?: futuresFeeArray["预付保证金"]?.dollar
                            totalPrice.subEx(deposit).subEx(bail)
                        }
                        else ->
                            BigDecimal(0)
                    }
                    futuresIntent.putExtra(Constants.DOLLAR, dollar.toDouble())
                }
                if (s.contains("尾款") && futuresFeeArray["预付保证金"]?.dollar.orEmpty() != 0.0) {
                    futuresIntent.putExtra(Constants.MARGIN, futuresFeeArray["预付保证金"]?.dollar.orEmpty())
                }
                activityForResult(futuresIntent) {
                    httpFuturesFee()
                }
            }
        }
    }

    /**
     * 货款
     */
    private fun httpFuturesFee(): Unit =
        httpGet<List<FuturesFeeBean>>(UrlConfig.PURCHASE_FUTURES_LIST, config = {
            listParams = listOf("purchaseProductId" to purchaseId)
        }) { futuresFeeList ->
            purchaseProductBean?.futuresFeeList = futuresFeeList
            futuresFee(futuresFeeList)
            updateBillTotalAmount()
        }

    private fun futuresFee(data: List<FuturesFeeBean>?) {
        futuresFeeArray.clear()
        data?.forEach {
            futuresFeeArray[it.feeType] = it
        }
        if (data.isNullOrEmpty()) {
            layout_futures.visibility = View.GONE
            return
        }
        layout_futures.visibility = View.VISIBLE
        table_layout.removeAllViews()
        table_layout.addView(inflater.inflate(R.layout.table_row_futures_fee_field, table_layout, false))
        futuresFeeList.forEach { type ->
            data.find {
                (it.feeType == type) && (type.contains("定金") || type.contains("尾款") || type.contains("保证金"))
            }?.let { futuresFeeBean ->
                val view = inflater.inflate(R.layout.table_row_futures_fee, table_layout, false)
                view.tv_type.contentText = futuresFeeBean.feeType
                view.tv_date.contentText = futuresFeeBean.date.goTimeFormat()
                view.tv_dollar.contentText = futuresFeeBean.dollar.toString()
                view.tv_rate.contentText = futuresFeeBean.exchangeRate.toString()
                view.tv_rmb.contentText = futuresFeeBean.rmb.toString()
                view.tv_handling_fee.contentText = futuresFeeBean.handlingFee.toString()
                view.tv_wire_transfer_fee.contentText = futuresFeeBean.wireTransferFee.toString()
                view.tv_total_fee.contentText = futuresFeeBean.totalFee.toString()
                view.onActionLongClicked(
                    "编辑" to {
                        activityForResult<FuturesFeeActivity>(
                            Constants.ACTION to Constants.ACTION_EDIT,
                            Constants.TITLE to futuresFeeBean.feeType,
                            Constants.MARGIN to futuresFeeArray["预付保证金"]?.dollar.orEmpty(),
                            Constants.DATA to futuresFeeBean
                        ) {
                            httpFuturesFee()
                        }
                    },
                    "删除" to {
                        httpGet<Any>(UrlConfig.FUTURES_FEE_DELETE, config = {
                            listParams = listOf("id" to futuresFeeBean.ID)
                        }) {
                            httpFuturesFee()
                        }
                    }
                )
                table_layout.addView(view)
            }
        }

        val deposit = futuresFeeArray["实际定金"]
        val balance = futuresFeeArray["实际尾款"]
        val bail = futuresFeeArray["实际保证金"]
        //总款 = 货款+手续费
        futuresFee = deposit?.totalFee.addEx(balance?.totalFee).addEx(bail?.totalFee).toDouble()
        //货款
        val productFee = deposit?.rmb.addEx(balance?.rmb).addEx(bail?.rmb)
        //手续费
        val serviceFee = deposit?.handlingFee.addEx(deposit?.wireTransferFee)
            .addEx(balance?.handlingFee.addEx(balance?.wireTransferFee))
            .addEx(bail?.handlingFee.addEx(bail?.wireTransferFee))

        val price = "$productFee + $serviceFee = $futuresFee"
        layout_futures_title.tv_fee.text = if (futuresFee != 0.0) "($price)" else ""

        //差额计算
        if (purchaseProductBean?.agentId == 2) { //泽厚的手续费放在清关费用中
            val depositDifference =
                futuresFeeArray["预付定金"]?.rmb.subEx(futuresFeeArray["实际定金"]?.rmb).toDouble()
            val depositText = if (depositDifference > 0) "多" else "欠"
            tv_deposit_difference.contentText = "定金差额：${depositText}${abs(depositDifference)}"

            val marginDifference =
                futuresFeeArray["预付保证金"]?.rmb.subEx(futuresFeeArray["实际保证金"]?.rmb).toDouble()
            val marginText = if (marginDifference > 0) "多" else "欠"
            tv_margin_difference.contentText = "保证金差额：${marginText}${abs(marginDifference)}"

            val balanceDifference =
                futuresFeeArray["预付尾款"]?.rmb.subEx(futuresFeeArray["实际尾款"]?.rmb).toDouble()
            val balanceStatus = if (balanceDifference > 0) "多" else "欠"
            tv_balance_difference.contentText = "尾款差额：${balanceStatus}${abs(balanceDifference)}"
        } else {

            //货款差额
            var depositFee = 0.0
            var balanceFee = 0.0
            var bailFee = 0.0
            purchaseProductBean?.settlementFeeList?.forEach {
                if (it.type.contains("定金")) {
                    depositFee += it.amount
                } else if (it.type.contains("尾款")) {
                    balanceFee += it.amount
                } else if (it.type.contains("保证金")) {
                    bailFee += it.amount
                }
            }

            val depositDifference = depositFee.subEx(futuresFeeArray["实际定金"]?.totalFee).toDouble()
            val depositText = if (depositDifference > 0) "多" else "欠"
            tv_deposit_difference.contentText = "定金差额：${depositText}${abs(depositDifference)}"

            val marginDifference = bailFee.subEx(futuresFeeArray["实际保证金"]?.totalFee).toDouble()
            val marginText = if (marginDifference > 0) "多" else "欠"
            tv_margin_difference.contentText = "保证金差额：${marginText}${abs(marginDifference)}"

            val balanceDifference = balanceFee.subEx(futuresFeeArray["实际尾款"]?.totalFee).toDouble()
            val balanceStatus = if (balanceDifference > 0) "多" else "欠"
            tv_balance_difference.contentText = "尾款差额：${balanceStatus}${abs(balanceDifference)}"
        }

        refreshFee()
    }

    /**
     * 融资费用
     */
    private fun httpFinancingFee(): Unit =
        httpGet<List<FinancingFeeBean>>(UrlConfig.PURCHASE_FINANCING_FEE_LIST, config = {
            listParams = listOf("purchaseId" to purchaseId)
        }) { financingFeeList ->
            purchaseProductBean?.financingFeeList = financingFeeList
            financingFee(financingFeeList)
            updateBillTotalAmount()
        }

    private fun financingFee(financingFeeList: List<FinancingFeeBean>?) {
        table_layout_financing.removeAllViews()
        table_layout_financing.visibility = View.GONE
        if (!financingFeeList.isNullOrEmpty()) {
            val view = inflater.inflate(
                R.layout.table_row_financing_fee_field,
                table_layout_financing,
                false
            )
            table_layout_financing.addView(view)
            table_layout_financing.visibility = View.VISIBLE
        }

        var amount = 0.0
        financingFeeList?.forEach {
            amount = amount.addEx(it.financingInterest).toDouble()
            val view =
                inflater.inflate(R.layout.table_row_financing_fee, table_layout_financing, false)
            view.find<TextView>(R.id.tv_type).contentText = it.financingType
            view.find<TextView>(R.id.tv_difference).contentText = it.financingAmount.toString()
            view.find<TextView>(R.id.tv_day).contentText = it.financingDays.toString()
            view.find<TextView>(R.id.tv_interest).contentText = it.financingInterest.toString()
            view.find<TextView>(R.id.tv_rate).contentText = it.financingRate.toString()
            view.find<TextView>(R.id.tv_times).contentText =
                it.startDate.goTimeFormat() + "\n" + it.endDate.goTimeFormat()
            view.onSingleLongClicked("编辑", "删除") { s ->
                if (s == "编辑") {
                    activityForResult<FinancingFeeEditActivity>(
                        Constants.TYPE to it.financingType,
                        Constants.DATA to it,
                        Constants.AGENT_ID to purchaseProductBean?.agentId
                    ) {
                        httpFinancingFee()
                    }
                } else if (s == "删除") {
                    httpGet<Any>(UrlConfig.PURCHASE_FINANCING_FEE_DELETE, config = {
                        listParams = listOf("id" to it.ID)
                    }) {
                        refreshFee()
                    }
                }
            }
            table_layout_financing.addView(view)
        }
        layout_financing.tv_fee.contentText = "(${amount})"
        financingFee = amount
        refreshFee()
    }


    /**
     * 税款
     */
    private fun httpTaxFee(): Unit = httpGet<TaxFeeBean>(UrlConfig.PURCHASE_TAX_DATA, config = {
        listParams = listOf("containerNo" to containerNo)
    }, result = { taxFeeBean ->
        purchaseProductBean?.taxFee = taxFeeBean
        taxFee(taxFeeBean)
        updateBillTotalAmount()
    })


    private fun taxFee(taxFeeBean: TaxFeeBean?) {
        if (taxFeeBean == null) {
            layout_tax.tv_fee.text = ""
            layout_tax_fee.visibility = View.GONE
            layout_tax.iv_add.visibility = View.VISIBLE
            return
        }
        layout_tax_fee.visibility = View.VISIBLE
        layout_tax_fee.onActionLongClicked(
            "编辑" to {
                activityForResult<TaxFeeActivity>(
                    Constants.TITLE to title,
                    Constants.DATA to purchaseProductBean?.taxFee,
                    Constants.PURCHASE_PRODUCT_ID to purchaseId,
                    Constants.CONTAINER_NO to containerNo,
                    Constants.TYPE to purchaseProductBean?.priceUnit
                ) {
                    httpTaxFee()
                }
            },
            "删除" to {
                messageDialog(msg = "是否删除税款？") { _, _ ->
                    httpGet<Any>(UrlConfig.PURCHASE_TAX_DELETE, config = {
                        listParams = listOf("id" to purchaseProductBean?.taxFee?.ID)
                    }) {
                        httpTaxFee()
                    }
                }
            }
        )
        tv_tax_day.text = taxFeeBean.date.goTimeFormat()
        tv_tax_rate.text = taxFeeBean.rate.toString()
        tv_tariff_fee.text = taxFeeBean.tariff.toString()
        tv_value_added_tax_fee.text = taxFeeBean.valueAddedTax.toString()
        tv_tax_difference_fee.text = taxFeeBean.taxDifference.toString()
        tr_rax_different.visibility =
            if (taxFeeBean.taxDifference != 0.0) View.VISIBLE else View.GONE
        val text =
            "${taxFeeBean.tariff.addEx(taxFeeBean.valueAddedTax)} + ${taxFeeBean.taxDifference} = ${taxFeeBean.totalFee}"
        layout_tax.tv_fee.contentText = "($text)"
        taxFee = taxFeeBean.totalFee
        refreshFee()
    }
}